<?php
/**
* @version		1.0
* @license		GNU/GPL 2.1
* @author		David Jonas
*/

// no direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

//Import JPlugin
jimport( 'joomla.plugin.plugin' );
require_once (JPATH_ROOT . DS . 'plugins' . DS . 'system' . DS . 'facebook-platform' . DS . 'php' . DS . 'facebook.php');
require_once (JPATH_ROOT . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php');

/**
 * AutoFacebook is a plugin that automatically posts new content on a Joomla! site to a facebook
 * account. 
 */
class plgSystemAutofacebook extends JPlugin
{
	protected $api_key = '';
	protected $secret  = '';
	protected $static_text	= '';
	protected $static_text_pos	= 0;
	protected $limit = 255;
	protected $post_modified = 0;
	protected $uid = '';

	/**
	 * Constructor
	 *
	 * @access	protected
	 * @param	object	$subject The object to observe
	 * @param 	array   $config  An array that holds the plugin configuration
	 * @since	1.0
	 */
	 
	 private function getSection($id)
	{
		$row =& JTable::getInstance('section');
		$row->load($id);

		return $row;
	}
	
	private function getCategory($id)
	{
		$row =& JTable::getInstance('category');
		$row->load($id);

		return $row;
	}
	
	// Helps with the Joomla url hell and creates corect url safeley.
	// Different cases for routing: frontend, backend, joomla not installed in route
	// Courtesy of AutoTweet
	 function fm_create_url($site_url)
	{
		// remove administrator string from path, if post is from backend (this is hell, why is joomla 1.5 routing and 				        basepath different in front- and backend?)
		$base_uri = JURI::base();
		$del_pos = JString::strrpos($base_uri, '/administrator/');
		if (FALSE === $del_pos) {
			// if access is form front end get only domain by this function, because routing returns roor foolder
			// [TODO]	make this more failsave for later joomla version (if they correct this, i will have trouble here!	
			$baseurl = JURI::getInstance()->toString(array ('scheme', 'host', 'port'));
		}
		else {
			$baseurl = substr_replace($base_uri, '', $del_pos);
		}
	
		// Joomla bug: different value for backend and frontend post (one with slash): correct this safely
		if ('/' != substr($site_url, 0, 1)) {
			// remove slash at the beginning                   
			$site_url = '/' . $site_url;
		}
	
		$url = $baseurl . $site_url;
		
		return $url;
	}

	function getURL($article)
	{
			$sec =& $this->getSection($article->sectionid);
			$cat =& $this->getCategory($article->catid);
			
			$sec_name	= '';
			$cat_name	= '';
			$sec_slug	= 0;
			$cat_slug	= 0;
			$id_slug	= $article->id . ':' . JFilterOutput::stringURLSafe($article->alias);			

			// post also correct url for article without section/category!
			if ($sec && $cat && (0 < $sec->id) && (0 < $cat->id)) {
				$sec_name = $sec->title;
				$cat_name = $cat->title;
				$sec_slug = $sec->id . ':' . JFilterOutput::stringURLSafe($sec->alias);
				$cat_slug = $cat->id . ':' . JFilterOutput::stringURLSafe($cat->alias);
			}
			
			// create url savely
			$article_url = JRoute::_(ContentHelperRoute::getArticleRoute($id_slug, $cat_slug, $sec_slug));
			$del_pos = JString::strrpos($article_url, '&amp;Itemid=');
			if (('' ==  $cat_name) && $del_pos) {
				// corrections for uncategorized articles (remove itemid from url)
				$article_url = substr_replace($article_url, '', $del_pos);
				$article_url = urldecode($article_url);
			}			
			
			$url = $this->fm_create_url(JRoute::_($article_url));
		$url=urlencode($url);
		$url = file_get_contents("http://api.adf.ly/api.php?key=960efda986269121420bb8d487dc90b6&uid=823949&advert_type=int&domain=adf.ly&url=".urlencode($url));
			
			return trim($url);
	}		
	 
	function plgSystemAutofacebook( &$subject, $params  )
	{
		global $mainframe;
		parent::__construct( $subject, $params  );

		// Get Plugin info
		$plugin			=& JPluginHelper::getPlugin('system', 'autofacebook');
		$pluginParams	= new JParameter($plugin->params);

		//populate this class
		$this->api_key = $pluginParams->get('api_key', '');
		$this->secret = $pluginParams->get('secret', '');
		$this->post_modified = (int)$pluginParams->get('post_modified', 0);
		$this->uid = $pluginParams->get('uid', '');
		$this->static_text = $pluginParams->get('static_text', '');
		$this->static_text_pos = (int)$pluginParams->get('static_text_pos', 0);
		$this->include_link = (int)$pluginParams->get('include_link', 0);
		// twitter
		$this->consumerKey 				= $pluginParams->get('consumerKey');
		$this->consumerSecret			= $pluginParams->get('consumerSecret');
		$this->accessToken				= $pluginParams->get('accessToken');
		$this->accessTokenSecret 		= $pluginParams->get('accessTokenSecret');
		include_once dirname(__FILE__).DS.'facebook-platform'.DS.'twitter.class.php';
	}

	function postMessage($article, $facebook)
	{
		global $mainframe;
		
		//Prepare the text
		$doPost = true;
		$title = $article->title;
		$msg = '';
		$url = $this->getURL($article);
		
		if($this->static_text != '')
		{
			switch($this->static_text_pos)
			{
				case 0:
					$msg = $title;
					break;
				case 1:
					$msg = $this->static_text.' '.$title;
					break;
				case 2:
					$msg = $title.' '.$this->static_text;
					break;
			}
		}
		else
		{
			$msg = $title;
		}
		
		if($this->include_link == 1)
		{
			$msg .= ' - '.$url;
		}
		
		try
		{
			if($facebook->api_client->users_hasAppPermission("publish_stream", $this->uid))
			{
				$facebook->api_client->stream_publish($msg, null, null, null, $this->uid);
				$mainframe->enqueueMessage('AutoFacebook - Facebook status has been updated!');
			}
			else
			{
				JError::raiseWarning('1', "You have no permission to set the status of this user");
				JError::raiseWarning('1', "To grant permition to the application login to facebook and visit:");
				JError::raiseWarning('1', "http://www.facebook.com/connect/prompt_permissions.php?api_key=".$this->api_key."&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=read_stream,publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=".$this->uid);
			}
		}
		catch(Exception $e)
		{
			JError::raiseWarning('1', ' - AutoFacebook error - ' . $e->getMessage());
		}
		//twitter
		try{
			$twitter = new Twitter($this->consumerKey, $this->consumerSecret, $this->accessToken, $this->accessTokenSecret);
			
			$res = $twitter->request('statuses/update', array('status' => $title.' '.$url,'wrap_links'=>true));
			//send direct message to followers
			$this->twitterDirectMessage($twitter,$title.' '.$url);
			
		}
		catch(Exception $e)
		{
			JError::raiseWarning('1', ' - AutoFacebook error - ' . $e->getMessage());
		}
	}

	/**
	 * Run the plugin when onAfterContentSave is triggered 
	 */
	function onAfterContentSave( &$article, $isNew )
	{
	    global $mainframe;
		//Check if AutoFacebook is configured
		if($this->api_key == '' || $this->secret == '' || $this->uid == '')
		{
			JError::raiseWarning('1', ' - AutoFacebook error - AutoFacebook is not configured properly. Please go to Plugin Manager and add your facebook API key, API secret and User ID');
			return false;
		}
		
		//Check if content is published
		if(($isNew	|| $this->post_modified) && ($article->state == 1))
		{
			$facebook = new Facebook($this->api_key, $this->secret);			
			$this->postMessage($article, $facebook);
		}
		
		return true;
	}
	function onAfterVideoApproval($video){
		global $mainframe;
		//Check if AutoFacebook is configured
		
		if($this->api_key == '' || $this->secret == '' || $this->uid == '')
		{
			JError::raiseWarning('1', ' - AutoFacebook error - AutoFacebook is not configured properly. Please go to Plugin Manager and add your facebook API key, API secret and User ID');
			return false;
		}
		
		//Check if content is published
		$facebook = new Facebook($this->api_key, $this->secret);			
		$this->postMessageVideo($video, $facebook);
		
		return true;
	}
	function postMessageVideo($video, $facebook)
	{
		global $mainframe;
		
		//Prepare the text
		$doPost = true;
		$title = 'makelovenow.info - '.$video->title;
		$msg = '';
		$url = $this->getVideoURL($video);
		
		if($this->static_text != '')
		{
			switch($this->static_text_pos)
			{
				case 0:
					$msg = $title;
					break;
				case 1:
					$msg = $this->static_text.' '.$title;
					break;
				case 2:
					$msg = $title.' '.$this->static_text;
					break;
			}
		}
		else
		{
			$msg = $title;
		}
		
		if($this->include_link == 1)
		{
			$msg .= ' - '.$url;
		}
		
		try
		{
			if($facebook->api_client->users_hasAppPermission("publish_stream", $this->uid))
			{
				$facebook->api_client->stream_publish($msg, null, null, null, $this->uid);
				$mainframe->enqueueMessage('AutoFacebook - Facebook status has been updated!');
				//die('ok');
			}
			else
			{
				JError::raiseWarning('1', "You have no permission to set the status of this user");
				JError::raiseWarning('1', "To grant permition to the application login to facebook and visit:");
				JError::raiseWarning('1', "http://www.facebook.com/connect/prompt_permissions.php?api_key=".$this->api_key."&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=read_stream,publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=".$this->uid);
				//echo "http://www.facebook.com/connect/prompt_permissions.php?api_key=".$this->api_key."&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=read_stream,publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=".$this->uid;die;
			}
		}
		catch(Exception $e)
		{
			JError::raiseWarning('1', ' - AutoFacebook error - ' . $e->getMessage());
			//echo JUtility::dump($video);
			//$msg =$e->getMessage();
			//die($msg);
		}		
		//twitter
		try{
			$twitter = new Twitter($this->consumerKey, $this->consumerSecret, $this->accessToken, $this->accessTokenSecret);
			
			$res = $twitter->request('statuses/update', array('status' => $title.' '.$url,'wrap_links'=>true));
			//send direct message to followers
			$this->twitterDirectMessage($twitter,$title.' '.$url);
			
		}
		catch(Exception $e)
		{
			JError::raiseWarning('1', ' - AutoFacebook error - ' . $e->getMessage());
		}
		
	}
	function getVideoURL($video){
		global $hwdvsItemid;
		$link= JURI::root().JRoute::_("index.php?option=com_hwdvideoshare&task=viewvideo&Itemid=".$hwdvsItemid."&video_id=".$video->id);
		$link=urlencode($link);
		$link = file_get_contents("http://api.adf.ly/api.php?key=960efda986269121420bb8d487dc90b6&uid=823949&advert_type=int&domain=adf.ly&url=".$link);
		
		return trim($link);
	}
	function twitterDirectMessage(&$twitter,$message){
		$fc= file_get_contents(dirname(__FILE__).DS.'twitterdelay.ini');
		$time = intval($fc);
		$time = $fc;
		//die($fc);
		if($time<time()){
			file_put_contents(dirname(__FILE__).DS.'twitterdelay.ini',time()+60*60);
			$follow = $twitter->getFollowers();
			foreach($follow->ids as $id)
			{
				//usleep(2000);	
				try{	
					//$res= $twitter->follow($id);
						$res = $twitter->request("direct_messages/new",array('user_id'=>$id,'text'=>$message));
				}
				catch(exception $e){
					
				}
				
			}
			
		}
	}
	function onAfterDispatch(){
		
		global $mainframe;
		$job = JRequest::getVar('job');
		if($job=='auto'){
			$db = JFactory::getDBO();
			global $limitstart, $isModerator, $hwdvsItemid, $hwdvs_joinv, $hwdvs_selectv;
			require_once(JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_hwdvideoshare'.DS.'config.hwdvideoshare.php');
			$c = hwd_vs_Config::get_instance();
			$db = & JFactory::getDBO();
						

			$limit     = intval($c->vpp);

			$where = ' WHERE video.approved = "pending"';

				$query = 'SELECT'.$hwdvs_selectv
				. ' FROM #__hwdvidsvideos AS video'
				. $hwdvs_joinv
				. $where
				. ' ORDER BY video.id '
			;
			$db->SetQuery($query, 0, 1);
			$row = $db->loadObject();
			//echo "index.php?option=com_hwdvideoshare&task=approvevideo&videoid=".$row->id;
			//echo JUtility::dump($row);die;
			if($row->id){
				$mainframe->redirect("index2.php?option=com_hwdvideoshare&task=approvevideo&job=autofacebook&videoid=".$row->id);
				$mainframe->close();
			}			
		}
	}
}
?>